package com.lz.autotest.common.utils.sql;

import com.lz.autotest.common.utils.SpringBeanUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * batch
 * @author zzz
 */
public class MybatisBatchUtil {
    static Logger logger = LoggerFactory.getLogger(MybatisBatchUtil.class);
 
    enum Action {
        INSERT("插入"),
        UPDATE("更新"),
        DELETE("删除");
        private String name;
 
        Action(String name) {
            this.name = name;
        }
 
        public String getName() {
            return name;
        }
    }
 
    public static <T> void batchInsert(String mybatisSQLId, List<T> list) {
        batchExecute(mybatisSQLId, list, Action.INSERT);
    }
 
    public static <T> void batchUpdate(String mybatisSQLId, List<T> list) {
        batchExecute(mybatisSQLId, list, Action.UPDATE);
    }
 
    public static <T> void batchDelete(String mybatisSQLId, List<T> list) {
        batchExecute(mybatisSQLId, list, Action.DELETE);
    }
 
    private static <T> void batchExecute(String mybatisSQLId, List<T> list, Action action) {
        SqlSessionFactory sessionFactory = SpringBeanUtils.getBean(SqlSessionFactory.class);
        SqlSession session = null;
        try {
            session = sessionFactory.openSession(ExecutorType.BATCH, false);
            Long startTime = System.currentTimeMillis();
 
            for (int i = 0; i < list.size(); i++) {
                switch (action) {
                    case INSERT:
                        session.insert(mybatisSQLId, list.get(i));
                        break;
                    case UPDATE:
                        session.update(mybatisSQLId, list.get(i));
                        break;
                    case DELETE:
                        session.delete(mybatisSQLId, list.get(i));
                        break;
                    default:
                        break;
                }
            }
 
            session.commit();
            session.clearCache();
            Long endTime = System.currentTimeMillis();
            logger.info("批量{}[{}]条数据，耗时：{}毫秒",
                    action.getName(), list.size(), (endTime - startTime));
        } catch (Exception e) {
            session.rollback();
            logger.error("batchCommit error!", e);
            throw e;
        } finally {
            if (null != session) {
                session.close();
                logger.debug("close session");
            }
        }
    }
 
}